import { widgetManager } from '@/common/managers';
import { getFaceIdsBySolidIds, i18n } from '@/common/utils';
import { IChangeEvent } from '@rjsf/core';
import { CmdDialogForm, KEYBOARD_KEY, userEvents } from 'nextcae-base';
import { useEffect, useState } from 'react';
import { schema, uiSchema } from './data';
import { NMMeshBaseCommand, TOOL_BAR_EVENT } from '@/common/types';
import { Button } from 'antd';
import { mesh } from '@/domain';
import { EntityInfo, EntityPartType } from '@amcax/web-render';
import Base from '@/common/cmdBase/cmdBase';
import { pickManager, SAVE_PICK_KEY } from '@/commands/bottomTools';
import { drawStyleInteractor } from '@/commands/bottomTools/drawstyle/DrawStyleInteractor';
export interface TopoDialogProps {
  title: string;
  onClose: () => void;
  icon?: string;
}
type ButtonArrType = {
  label: string;
  icon?: any;
  position?: 'start' | 'end';
  disabled?: boolean;
  onClick?: () => void;
  type?: 'primary' | 'text' | 'default';
}[];
// 面网格
export function Command({ title, onClose, icon }: TopoDialogProps) {
  const [hintMessage, setHint] = useState('进入合并节点命令,请选择节点');
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState<any>({
    Settings: {
      tol: 0,
    },
    Option: {
      mergeTo: 1,
      save: 1,
    },
    Selection: { source: [] },
    SourceType: 'Node',
  });

  useEffect(() => {
    drawStyleInteractor.initChange('shadow', false, 0.4);
    window.addEventListener('keyup', onKeyUp);
    return () => {
      window.removeEventListener('keyup', onKeyUp);
      drawStyleInteractor.initChange('shadow', true, 1);
      init();
    };
  }, []);

  useEffect(() => {
    widgetManager.hint(hintMessage);
    return () => {
      widgetManager.hint();
    };
  }, [hintMessage]);

  const onKeyUp = (e: KeyboardEvent) => {
    // 点击键盘ESC退出命令
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  };
  function getSourceType(type) {
    switch (type) {
      case EntityPartType.node:
        return {
          type: 'Node',
          hint: '节点',
        };
      case EntityPartType.element:
        return {
          type: 'Element',
          hint: '单元',
        };
      case EntityPartType.face:
        return {
          type: 'Part',
          hint: '部件',
        };
      default:
        return {
          type: 'Node',
          hint: '节点',
        };
    }
  }
  const handleResultSelectChange = (data: IChangeEvent, pickType: string) => {
    if (pickType in EntityPartType) {
      // 选中模型
      pickManager()
        .getPickSelect()
        .setEntsSelected(false, SAVE_PICK_KEY.TEMP, true);
      const { type, hint } = getSourceType(pickType);
      data.formData.SourceType = type;
      setHint('进入合并节点命令,请选择' + hint);
    }
    if (data.formData.Selection.source.length > 0) {
      setIdentify(true);
    } else {
      setIdentify(false);
      setExecute(false);
    }
    setFormData(data.formData);
    if (pickType === 'face') {
      userEvents.emit(TOOL_BAR_EVENT.RANGE_BTM_SELECTED, 'draw-part');
    }
  };
  const [execute, setExecute] = useState(false);
  const [identify, setIdentify] = useState(false);
  const buttonArr = (disabled1, disabled2): ButtonArrType => [
    {
      label: '识别',
      disabled: disabled1,
      type: 'primary',
      onClick: () => {
        setExecute(true);
      },
    },
    {
      label: '预览',
      disabled: disabled1 || disabled2,
      type: 'primary',
      onClick: () => {
        commend(true);
      },
    },
    {
      label: '合并',
      disabled: disabled1 || disabled2,
      onClick: () => {
        commend(false);
      },
    },
    {
      label: '取消',
      onClick: () => {
        onClose();
      },
    },
  ];
  const commend = async (preview: boolean = false) => {
    const source = [];
    formData.Selection.source.forEach((item: EntityInfo) => {
      if (item.type === EntityPartType.solid) {
        const faceIds = getFaceIdsBySolidIds([item.idx]);
        source.push(
          ...faceIds.map((item) =>
            Base.makeIdNew({
              type: EntityPartType.face,
              idx: item,
              dxid: undefined,
            }),
          ),
        );
      } else {
        source.push(Base.makeIdNew(item));
      }
    });
    const params = {
      SourceType: formData.SourceType, // 源类型Node, Element, part
      Source: source,
      Tol: formData.Settings.tol,
      MergeTo: formData.Option.mergeTo,
      Save: formData.Option.save,
      Preview: preview, // 是否预览
    };
    try {
      setIsLoading(true);
      const nodeIds = await mesh.mergeNode(params);
      if (!preview) {
        init();
        setFormData((state) => ({ ...state, Selection: { source: [] } }));
      } else {
        onPreview(nodeIds, formData.SourceType);
      }
    } finally {
      setIsLoading(false);
    }
  };
  const init = () => {
    setExecute(false);
    setIdentify(false);
    pickManager()
      .getPickSelect()
      .setEntsSelected(false, SAVE_PICK_KEY.TEMP, true);
  };
  const onPreview = (nodeIds: string[], SourceType: string) => {
    const ents: EntityInfo[] = [];
    nodeIds.forEach((item) => {
      const [type, idx] = item.split('_');
      ents.push({
        type: type.toLocaleLowerCase() as EntityPartType,
        idx: +idx,
        dxid: undefined,
      });
    });
    if (SourceType === 'Node') {
      setFormData((state) => ({ ...state, Selection: { source: ents } }));
    } else {
      pickManager()
        .getPickSelect()
        .setEntsSelected(true, SAVE_PICK_KEY.TEMP, false, ents);
    }
  };

  return (
    <CmdDialogForm
      title={title}
      formData={formData}
      titleIcon={icon}
      submitLoading={isLoading}
      onChange={handleResultSelectChange}
      schema={schema}
      extraUiSchema={uiSchema}
      onClose={onClose}
      footerChildren={
        <div className='justify-end pr-5 pb-2 flex gap-2 border-t-[1px] pt-2'>
          {buttonArr(!identify, !execute).map((item, index) => {
            return (
              <>
                <Button
                  type={item.type}
                  icon={item.icon}
                  iconPosition={item?.position}
                  key={index}
                  disabled={item?.disabled ?? false}
                  onClick={item.onClick}>
                  {item.label}
                </Button>
              </>
            );
          })}
        </div>
      }></CmdDialogForm>
  );
}
// SurfaceMesh 面网格
export const cmdMergeNode: NMMeshBaseCommand = {
  id: 'cmdMergeNode',
  icon: 'commands/mesh/merge-node',
  label: 'command.mesh.nodeMerge',
  create: (label: string, onClose: () => void) => (
    <Command
      title={i18n.t(label)}
      onClose={onClose}
      icon={cmdMergeNode.icon}
    />
  ),
};
